package com.unionftech.common.base.mvp.impl

import android.content.Context
import android.os.Bundle
import com.unionftech.common.base.BaseActivity
import com.unionftech.common.base.mvp.IBaseView
import com.unionftech.common.base.mvp.proxy.ProxyMvpActivity
import java.util.concurrent.atomic.AtomicInteger

abstract class BaseMvpActivity : BaseActivity(), IBaseView {
    private lateinit var mProxyMvpActivity: ProxyMvpActivity<in IBaseView>
    private var mCounter: AtomicInteger? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    private fun createProxyActivity(): ProxyMvpActivity<in IBaseView> {
        if (!::mProxyMvpActivity.isInitialized) {
            return ProxyMvpActivity(this)
        }
        return mProxyMvpActivity
    }

    override fun initData() {
        mProxyMvpActivity = createProxyActivity()
        mProxyMvpActivity.bindPresenter()
    }

    fun setBothRequestCounter(count: Int) {
        mCounter = AtomicInteger(count)
    }

    private fun isBothRequestFinish(): Boolean {
        return mCounter == null || mCounter!!.decrementAndGet() == 0
    }

    override fun onDestroy() {
        super.onDestroy()
        mProxyMvpActivity.unbindPresenter()
        hideLoading()
    }

    override fun getContext(): Context {
        return this
    }

    override fun showLoading() {
        if (needShowLoading()) {
            super.showLoading()
        }
    }

    override fun hideLoading() {
        if (isBothRequestFinish()) {
            runOnUiThread {
                mCounter = null
                super.hideLoading()
            }
        }
    }

    open fun needShowLoading(): Boolean {
        return true
    }
}